import 'package:safety_platform/models/task.dart';
import 'package:intl/intl.dart';
import 'package:safety_platform/http.dart';
import 'package:safety_platform/models/attachment.dart';

final String _url = '/inspection/tasks/';

class TaskRepository {
  Future<Task> getTaskDetail(String taskId) async {
    final String url = '$_url$taskId/';

    dynamic res = await httpGet(url);

    return Task.fromJson(res);
  }

  Future<Task> submitTask(Task task) async {
    final String url = '$_url${task.id}/';

    final dynamic data = task.toJson();
    data['description'] = '293939399393939393';

    List items = [];
    for (TaskItem item in task.items) {
      Map<String, dynamic> itemMap = {
        'id': item.id,
        'result': item.result,
        'remark': item.remark,
      };

      if (item.attachments != null && item.attachments.length >= 0) {
        itemMap['attachments'] = item.attachments
            .map((Attachment attachment) => {'id': attachment.id})
            .toList();
      }
      items.add(itemMap);
    }
    data['items'] = items;
    print('提交任务数据: $data');

    dynamic res = await httpPut(url, data: data);

    return Task.fromJson(res);
  }

  Future<TaskPage> loadTodayTask({int page: 1, int pageSize: 10}) async {
    DateTime now = DateTime.now();
    DateFormat formatter = DateFormat('yyyy-MM-dd');

    Map<String, String> data = {
      'date_published': formatter.format(now),
    };
    dynamic pageData = await httpGet(_url, data: data);

    return TaskPage.fromJson(pageData);
  }
}
